import websocket
from threading import Thread
import time
import sys

gKBs = 0
start_time = time.time()
wsConnected = False
ws = None

def on_error(ws, error):
  print(error)
 
def on_close(ws):
  print("### closed ###")
 
def on_open(ws):
  print("on_open")
  global wsConnected
  wsConnected = True
 
proflie_ts =  time.time()
def on_data(ws, message, type, flag):
  print("on_data msg rec: ")
  print(message)
  global proflie_ts
  global gKBs
  gKBs = gKBs + 1
  speed = gKBs /(time.time() - start_time)
  #print(message)
  print("rec ts_span:",'%.1f' % ((time.time() - proflie_ts)*1000), "speed",'%.3f' % speed, "KB/s")
  proflie_ts = time.time()
 

def waitConnected():
  waitCnt = 1000
  for i in range(waitCnt):
    if (wsConnected != True):
      time.sleep(0.005)
    else:
      break
  return wsConnected

def wsInit(ws_url, customOnData = None):
  print("wsInit")
  def runwsLoop(*args):
    global ws
    websocket.enableTrace(True)
    OnDataFunc = None
    if customOnData is not None:
      OnDataFunc = customOnData
    else:
      OnDataFunc = on_data
    ws = websocket.WebSocketApp(ws_url,
                  #on_message=on_message,
                  on_error = on_error,
                  on_close = on_close,
                  on_data = OnDataFunc,
                  on_open = on_open)
    # send the message, then wait
    # so thread doesn't exit and socket
    # isn't closed
    ws.run_forever()
    time.sleep(10000)
  Thread(target=runwsLoop).start()

  
  if not waitConnected():
    print("Error connect time out!")

def wsRequest(req):
  ws.send(req)

def wsSetRepeatRequest(req):
  print("SetRepeatRequest")
  def run(*args):
    # send the message, then wait
    # so thread doesn't exit and socket
    # isn't closed
    print("send: setRepeatRequest")
    global start_time
    start_time = time.time()
    ws.send(req)
  Thread(target=run).start()

#
#wsInit("ws://192.168.1.103/")
#wsRequest("test")

